package com.situ.mall.order.listener;

import com.situ.mall.common.constant.MqConstant;
import com.situ.mall.common.util.MultiDelayMessage;
import com.situ.mall.order.service.IOrderInfoService;
import com.situ.mall.pojo.entity.order.OrderInfo;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class OrderStatusListener {

    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(MqConstant.DELAY_ORDER_QUEUE),
            exchange = @Exchange(name = MqConstant.DELAY_EXCHANGE, delayed = "true"),
            key = MqConstant.DELAY_ORDER_ROUTING_KEY
    ))
    public void listenDelayMessage(MultiDelayMessage<Long> message) {
        System.out.println("OrderStatusListener.listenDelayMessage message:" + message);
        //1.获取消息中的订单id
        Long orderId = message.getData();
        //2.查询订单，判断状态：0是未支付，大于0则是已经支付
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        //订单不存在或者订单已经支付
        if (orderInfo == null || orderInfo.getOrderStatus() > 0) {
            return;
        }
        //3.订单未支付，判断是否还有剩余延迟时间
        if (message.hasNextDelay()) {
            //有延迟时间，需要重新发送延迟消息，先获取延迟时间的int值，发送延时消息
            int delayValue = message.removeNextDelay().intValue();
            rabbitTemplate.convertAndSend(MqConstant.DELAY_EXCHANGE, MqConstant.DELAY_ORDER_ROUTING_KEY, message, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    message.getMessageProperties().setDelay(delayValue);
                    return message;
                }
            });
            return;
        }
        //4.没有剩余延迟时间，说明订单超时未支付
        orderInfoService.cancelOrder(orderId);
    }
}
